import { Channel } from '@/types/data'
import { AxiosResponse } from 'axios'
import { hasToken, setChannels } from '@/utils/storage'
import request from '@/utils/request'
import { RootThunkAction } from '@/types/store'
import { getChannels as getChannelsStorage } from '@/utils/storage'
import { HomeAction } from '@/types/store'

// 获取频道列表的action函数
export const getChannels = (): RootThunkAction => {
  return async (dispatch) => {
    // 判断用户是否登录
    if (hasToken()) {
      // 登录
      const res = await request.get('/user/channels')
      const { channels } = res.data.data
      dispatch({
        type: 'home/saveChannels',
        payload: channels,
      })
    } else {
      // 未登录
      const channels = getChannelsStorage()
      if (channels.length) {
        dispatch({
          type: 'home/saveChannels',
          payload: channels,
        })
      } else {
        const res = await request.get('/user/channels')
        const { channels } = res.data.data
        dispatch({
          type: 'home/saveChannels',
          payload: channels,
        })
        setChannels(channels)
      }
    }
  }
}

export const getAllChannels = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<AxiosResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    dispatch({
      type: 'home/saveAllChannels',
      payload: res.data.data.channels,
    })
  }
}

export const setChannelActive = (payload: number): HomeAction => {
  return {
    type: 'home/setChannelActive',
    payload,
  }
}

export const addChannel = (item: Channel): RootThunkAction => {
  return (dispatch, getState) => {
    let channels: Channel[] = []
    if (hasToken()) {
      // 有token 发请求
      console.log('发请求')
    } else {
      // 没有token 存本地
      channels = [...getState().home.channels, item]
      setChannels(channels)
    }
    // redux存
    dispatch({
      type: 'home/saveChannels',
      payload: channels,
    })
  }
}
